package com.example.filter;

import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpHeaders;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpRequestDecorator;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.List;

@Component
public class TokenFilter implements GlobalFilter, Ordered {
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpRequest request = exchange.getRequest();
        String path = request.getPath().value();

        // 如果不是目标路径，则继续处理
        if (!path.startsWith("/auth/admin/login")) {
            List<String> tokens = request.getHeaders().getOrEmpty("token");
            if (CollectionUtils.isEmpty(tokens)) {
                tokens = request.getQueryParams().get("access_token");
            }
            if (!CollectionUtils.isEmpty(tokens)) {
                // 修改请求头，添加Bearer token
                List<String> finalTokens = tokens;
                ServerHttpRequest modifiedRequest = new ServerHttpRequestDecorator(request) {
                    @Override
                    public HttpHeaders getHeaders() {
                        HttpHeaders httpHeaders = new HttpHeaders();
                        httpHeaders.putAll(super.getHeaders());
                        // 清除原来的token header，并设置新的Authorization header
                        httpHeaders.remove("token");
                        httpHeaders.set("Authorization", "Bearer " + finalTokens.get(0));
                        return httpHeaders;
                    }
                };
                // Spring WebFlux 中用于创建 ServerWebExchange 对象的一个新实例的方法链，主要用于在不改变原始请求的情况下修改请求内容。
                return chain.filter(exchange.mutate().request(modifiedRequest).build());
            }
        } else{
            List<String> tokens = request.getHeaders().getOrEmpty("token");
            if (!tokens.isEmpty()) {
                // 修改请求头，添加Bearer token
                ServerHttpRequest modifiedRequest = new ServerHttpRequestDecorator(request) {
                    @Override
                    public HttpHeaders getHeaders() {
                        HttpHeaders httpHeaders = new HttpHeaders();
                        httpHeaders.putAll(super.getHeaders());
                        httpHeaders.remove("token");
                        return httpHeaders;
                    }
                };
                // Spring WebFlux 中用于创建 ServerWebExchange 对象的一个新实例的方法链，主要用于在不改变原始请求的情况下修改请求内容。
                return chain.filter(exchange.mutate().request(modifiedRequest).build());
            }
        }
        return chain.filter(exchange);
    }

    // 配置过滤的执行顺序，越小要早执行
    @Override
    public int getOrder() {
        return 0;
    }
}
